package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: ArticleFreemarkerServiceImpl
 * Description:
 * date: 2023/8/11 0011 18:01
 *
 * @author zHan
 */
@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 将静态文件上传到minio
     *
     * @param article
     * @param content
     */
    @Override
    @Async  // 异步调用
    public void buildArticleDetailToMinio(ApArticle article, String content) {
        // 获取文章内容
        if (content != null && StringUtils.isNotBlank(content)) {
            // 文章内容通过freemarker生成html文件
            Template template = null;
            // 输出流
            StringWriter writer = new StringWriter();
            try {
                template = configuration.getTemplate("article.ftl");
                // 准备数据模型
                Map<String, Object> contentDataModel = new HashMap<>();
                contentDataModel.put("content", JSONArray.parseArray(content));

                template.process(contentDataModel, writer);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            // 把html文件上传到minio中
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", article.getId() +
                    ".html", inputStream);
            // 修改ap_article表，保存static_url字段
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,
                    article.getId()).set(ApArticle::getStaticUrl, path));

            // 发送消息，创建es索引
            createArticleESIndex(article,content,path);
        }
    }

    /**
     * 发送消息，创建es索引
     * @param article
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle article, String content, String path) {
        // 封装vo对象
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(article,searchArticleVo);
        searchArticleVo.setContent(content);
        searchArticleVo.setStaticUrl(path);
        // 发送消息
        String msg = JSON.toJSONString(searchArticleVo);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,msg);
    }
}
